package org.bt.common.validator;

import org.bt.common.validator.aspect.Pattern;
import org.hibernate.validator.internal.util.logging.Log;
import org.hibernate.validator.internal.util.logging.LoggerFactory;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.invoke.MethodHandles;
import java.util.regex.Matcher;
import java.util.regex.PatternSyntaxException;

/**
 * PatternValidator
 * <p>
 * Created on 2020/1/9
 *
 * @author tongw
 */
public class PatternValidator implements ConstraintValidator<Pattern, CharSequence> {

    private static final Log LOG = LoggerFactory.make(MethodHandles.lookup());
    private java.util.regex.Pattern pattern;
    private String escapedRegexp;

    public PatternValidator() {
    }

    @Override
    public void initialize(Pattern parameters) {
        Pattern.Flag[] flags = parameters.flags();
        int intFlag = 0;
        Pattern.Flag[] var4 = flags;
        int var5 = flags.length;

        for (int var6 = 0; var6 < var5; ++var6) {
            Pattern.Flag flag = var4[var6];
            intFlag |= flag.getValue();
        }

        try {
            this.pattern = java.util.regex.Pattern.compile(parameters.regexp(), intFlag);
        } catch (PatternSyntaxException var8) {
            throw LOG.getInvalidRegularExpressionException(var8);
        }

        this.escapedRegexp = InterpolationHelper.escapeMessageParameter(parameters.regexp());
    }

    @Override
    public boolean isValid(CharSequence value, ConstraintValidatorContext constraintValidatorContext) {
        if (value == null) {
            return true;
        } else {
            Matcher m = this.pattern.matcher(value);
            return m.matches();
        }
    }
}
